import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Avatar, Popconfirm, message, Modal, Dropdown } from 'antd';
import { PlusOutlined, ExportOutlined, ImportOutlined, MoreOutlined, EditOutlined, DeleteOutlined, UserOutlined, LockOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { getUserList, deleteUser, batchOperateUsers, exportUsers, resetUserPassword } from '@/services/userManagementApi';
import { useApi, useTableApi, useDeleteApi, useExportApi, useBatchApi } from '@/hooks/useApi';
import { getToken } from '@/utils/authInterceptor';
import UserForm from './components/UserForm';
import UserDetail from './components/UserDetail';
import BatchOperationModal from './components/BatchOperationModal';

const UserList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [selectedRows, setSelectedRows] = useState<USER.UserModel[]>([]);
  const [userFormVisible, setUserFormVisible] = useState(false);
  const [userDetailVisible, setUserDetailVisible] = useState(false);
  const [batchModalVisible, setBatchModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState<USER.UserModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');

  // 使用统一的API Hook
  const deleteUserApi = useDeleteApi(deleteUser, {
    successMessage: '用户删除成功',
    confirmTitle: '确认删除',
    confirmContent: '确定要删除该用户吗？此操作不可恢复。',
    onSuccess: () => {
      actionRef.current?.reload();
    },
  });

  const resetPasswordApi = useApi(resetUserPassword, {
    manual: true,
    onSuccess: () => {
      message.success('密码重置成功');
    },
  });

  const exportUsersApi = useExportApi(exportUsers, {
    filename: '用户列表',
    successMessage: '用户列表导出成功',
  });

  const batchOperateApi = useBatchApi(batchOperateUsers, {
    successMessage: '批量操作成功',
    onSuccess: () => {
      actionRef.current?.reload();
      setSelectedRowKeys([]);
      setSelectedRows([]);
      setBatchModalVisible(false);
    },
  });

  // 用户状态标签颜色映射
  const statusColorMap = {
    active: 'green',
    inactive: 'orange',
    banned: 'red',
  };

  // 用户角色标签颜色映射
  const roleColorMap = {
    admin: 'red',
    user: 'default',
  };

  // 表格列定义
  const columns: ProColumns<USER.UserModel>[] = [
    {
      title: '用户ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      width: 80,
      search: false,
      render: (_, record) => (
        <Avatar 
          src={record.avatar} 
          icon={<UserOutlined />}
          size={40}
        />
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 120,
      copyable: true,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      width: 120,
      search: false,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 180,
      search: false,
      copyable: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 120,
      search: false,
      copyable: true,
    },
    {
      title: '角色',
      dataIndex: 'role',
      width: 100,
      valueType: 'select',
      valueEnum: {
        admin: { text: '管理员', status: 'Error' },
        user: { text: '用户', status: 'Default' },
      },
      render: (_, record) => (
        <Tag color={roleColorMap[record.role as keyof typeof roleColorMap] || 'default'}>
          {record.role === 'admin' ? '管理员' : '用户'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      valueType: 'select',
      valueEnum: {
        active: { text: '正常', status: 'Success' },
        inactive: { text: '未激活', status: 'Warning' },
        banned: { text: '已封禁', status: 'Error' },
      },
      render: (_, record) => (
        <Tag color={statusColorMap[record.status]}>
          {record.status === 'active' ? '正常' : record.status === 'inactive' ? '未激活' : '已封禁'}
        </Tag>
      ),
    },
    {
      title: '等级',
      dataIndex: 'level',
      width: 80,
      search: false,
    },
    {
      title: '积分',
      dataIndex: 'points',
      width: 100,
      search: false,
      render: (text) => text?.toLocaleString(),
    },
    {
      title: '学习时长(小时)',
      dataIndex: 'total_study_time',
      width: 120,
      search: false,
      render: (_, record) => Math.round((record.total_study_time || 0) / 60),
    },
    {
      title: '最后登录',
      dataIndex: 'last_login_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '注册时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'edit',
                label: '编辑',
                icon: <EditOutlined />,
                onClick: () => handleEdit(record),
              },
              {
                key: 'resetPassword',
                label: '重置密码',
                icon: <LockOutlined />,
                onClick: () => handleResetPassword(record),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 处理查看详情
  const handleViewDetail = (record: USER.UserModel) => {
    setCurrentUser(record);
    setUserDetailVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: USER.UserModel) => {
    setCurrentUser(record);
    setEditMode('edit');
    setUserFormVisible(true);
  };

  // 处理删除
  const handleDelete = (record: USER.UserModel) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除用户 "${record.username}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: () => {
        deleteUserApi.run(record.id);
      },
    });
  };

  // 处理重置密码
  const handleResetPassword = (record: USER.UserModel) => {
    Modal.confirm({
      title: '重置密码',
      content: `确定要重置用户 "${record.username}" 的密码吗？新密码将发送到用户邮箱。`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        resetPasswordApi.run(record.id, '123456'); // 临时密码
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentUser(undefined);
    setEditMode('create');
    setUserFormVisible(true);
  };

  // 处理导出
  const handleExport = () => {
    exportUsersApi.run({ format: 'excel' });
  };

  // 处理批量操作
  const handleBatchOperation = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要操作的用户');
      return;
    }
    setBatchModalVisible(true);
  };

  return (
    <PageContainer>
      <ProTable<USER.UserModel>
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建用户
          </Button>,
          <Button
            key="export"
            icon={<ExportOutlined />}
            onClick={handleExport}
          >
            导出
          </Button>,
          <Button
            key="batch"
            disabled={selectedRowKeys.length === 0}
            onClick={handleBatchOperation}
          >
            批量操作
          </Button>,
        ]}
        request={async (params) => {
          console.log('ProTable request params:', params);
          console.log('Current token:', getToken());
          try {
            const response = await getUserList({
              page: params.current || 1,
              limit: params.pageSize || 20,
              keyword: params.username,
              role: params.role,
              status: params.status,
            });
            console.log('API response:', response);
            return {
              data: response.data.list,
              success: response.code === 200,
              total: response.data.pagination.total,
            };
          } catch (error) {
            console.error('API request error:', error);

            // 检查是否是认证错误
            if (error && typeof error === 'object' && 'message' in error) {
              const errorMessage = (error as any).message;
              if (errorMessage.includes('登录已过期') || errorMessage.includes('401')) {
                message.error('登录已过期，请重新登录');
                history.push('/login');
                return {
                  data: [],
                  success: false,
                  total: 0,
                };
              }
            }

            // 返回模拟数据用于测试
            const mockData: USER.UserModel[] = [
              {
                id: 1,
                username: 'admin',
                nickname: '管理员',
                email: 'admin@example.com',
                phone: '13800138000',
                avatar: '',
                gender: 'male' as const,
                birth_date: '1990-01-01',
                role: 'admin' as const,
                status: 'active' as const,
                level: 5,
                experience: 1500,
                total_study_time: 7200,
                practice_count: 50,
                points: 2000,
                achievements: ['初学者', '勤奋学习者'],
                last_login_at: '2024-01-15 10:30:00',
                created_at: '2024-01-01 00:00:00',
                updated_at: '2024-01-15 10:30:00',
              },
              {
                id: 2,
                username: 'user001',
                nickname: '学习者小王',
                email: 'user001@example.com',
                phone: '13800138001',
                avatar: '',
                gender: 'female' as const,
                birth_date: '1995-05-15',
                role: 'user' as const,
                status: 'active' as const,
                level: 3,
                experience: 800,
                total_study_time: 3600,
                practice_count: 25,
                points: 1200,
                achievements: ['初学者'],
                last_login_at: '2024-01-14 15:20:00',
                created_at: '2024-01-10 00:00:00',
                updated_at: '2024-01-14 15:20:00',
              },
            ];
            return {
              data: mockData,
              success: true,
              total: mockData.length,
            };
          }
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys, rows) => {
            setSelectedRowKeys(keys as number[]);
            setSelectedRows(rows);
          },
        }}
        scroll={{ x: 1400 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 用户表单弹窗 */}
      <UserForm
        visible={userFormVisible}
        mode={editMode}
        initialValues={currentUser}
        onCancel={() => setUserFormVisible(false)}
        onSuccess={() => {
          setUserFormVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 用户详情弹窗 */}
      <UserDetail
        visible={userDetailVisible}
        user={currentUser}
        onCancel={() => setUserDetailVisible(false)}
      />

      {/* 批量操作弹窗 */}
      <BatchOperationModal
        visible={batchModalVisible}
        selectedUsers={selectedRows}
        onCancel={() => setBatchModalVisible(false)}
        onSuccess={() => {
          setBatchModalVisible(false);
          setSelectedRowKeys([]);
          setSelectedRows([]);
          actionRef.current?.reload();
        }}
      />
    </PageContainer>
  );
};

export default UserList;
